<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

/**
 * News model.
 */

class UserModel extends NewzanModel{

	protected $tableName = 'users';
    
	/* table columns */
    protected $fields = array();

	/* validations definitions */

    protected $_validate = array();

    protected $_auto = array();
    
    public function getUserSubScribe($nick , $article_code)
    {
    	$params = array(
    			'nick' => $nick,
    			'article_code' => $article_code
    	);
    	
    	$res = $this->_api->VasSubscribeGetRequest($params);
    	$subscribe_records = (array) $res['article_user_subscribes']->article_user_subscribe;
    	if( !empty($subscribe_records) ){
    		$subscribe_records = json_decode( json_encode($subscribe_records) , true );
    		//判断版本，并且返回版本权限最高的那个订购版本
    		$avilable_versions = C('ZTC_ROLES');
    		$final_version = array(
    				'name' => '未知版本',
    				'level' => 0
    		);
    		foreach( $subscribe_records as $record){
    			if ( array_key_exists( $record['item_code'] , $avilable_versions ) ){
    				$final_version =  $avilable_versions[ $record['item_code'] ];
    				$final_version['item_code'] = $record['item_code'];
    				$final_version['deadline'] = $record['deadline'];
    			}
    		}
    		return $final_version;
    	}else{
    		return array();
    	}
    }
    
    public function getUserCid($user_id)
    {
        //通过产品你分类来判断店铺所在主要分类
        //first check 数据库
        $products = M('products')->where( array( 'user_id' => $user_id) )->field('cid')->order('rand()')->limit(100)->select();
        $user = $this->where( array( 'user_id' => $user_id) )->find();
        if($user){
            $cid = $user['cid'];
            
            //if cid ==0 通过api来查询cid
            if(!$cid){
                $params = array(
                    'fields' => 'sid,cid,title,nick,desc,bulletin,pic_path,created,modified'
                );
                $res = $this->_api->ShopGetRequest($params);
                $shop = (array) $res['shop'];
                $cid = $shop['cid'];
                //update database
                $this->where( array( 'user_id' => $user_id) )->save( array('cid' => $cid) );
            }
            
        }
        
        return $cid;
    }

	/**
	 * 获取所有购买还未过期的用户ID列表.
	 * 
	 * @param bool[=0] $onlyAuto 是否只获取带自动开车功能的用户。默认为false。 
	 * @return false|array1D
	 */
    public function getValidUserIds($onlyAuto = false)
    {
		$whr = array('purchase_expires' => array('gt', date('Y-m-d H:i:s')), 'init' => array('neq', 0));
		if($onlyAuto && defined('MANUAL_VERSIONS'))
			$whr['item_code'] = array('not in', explode(',', MANUAL_VERSIONS));
		return $this->where($whr)->getField('user_id', true);	
    }

    /**
     * 
     * 获取一个可用的oauth权限的用户用来执行api的查词请求
     */
    
    public function getAvailableUserForApi($num = 1)
    {
        // $oauth = M('oauth')->order('oauth_time desc')->find();
        $sql = "SELECT 
                    oauth.* 
                FROM oauth 
                INNER JOIN users ON users.user_id = oauth.taobao_user_id AND users.authorized_to = 0 AND users.type <> \"\" AND users.balance > 0 
                ORDER BY oauth.oauth_time DESC LIMIT 1";
        $oauth=$this->query($sql);
        // find user
        if( !$oauth ) return false;
        $user = $this->where( 'user_id = ' . $oauth[0]['taobao_user_id'] )->find();
        // 确定是不是代理用户，是的话找一个他代理的人进的名字
        // if(!empty($user['authorized_users'])) {
        //     $user = $this->where('authorized_to = ' . $oauth['taobao_user_id'])->order('RAND()')->find();
        // }
        return array( 'oauth' => $oauth[0] , 'user' => $user );
    }
    
    /**
     * 给指定的用户创建session. 适用于客户端没法登录, 完全自己掌控的情况.
     * 
     * @param int $userId 用户ID.
     * @param int $managerId [可选] 授权给的用户ID. 如果给定, 则利用该用户的oauth.
     */
    public function setAuth($userId, $managerId = 0)
    {
    	$me = $this->getUserByTaobaoId($userId);
    	if(!$managerId && $me['authorized_to'])
    		$managerId = $me['authorized_to'];
    	$manager = $managerId ? $this->getUserByTaobaoId($managerId) : null;
    	if(!$me || ($managerId && !$manager)) {
    		throw new NewzanException("用户$userId或者授权给的用户$managerId不存在",RetStatus::PARAM_ERR);
    	}
    	// get user access token
    	$oauth = D('oauth')->where(array('taobao_user_id' => ($managerId ? $managerId : $userId)))->find();
    	if(!$oauth || ($oauth['oauth_time'] + $oauth['expires_in'] < time()+5)) { // 至少还有5s才过期 
    		throw new NewzanException('无法获取oauth权限或者oauth已经过期.', 403);
    	} else {
    		$managerAv = true;
    		// if($managerId) {
    		// 	$apiAuthUserNicks = $this->getAuthorizedUsers($oauth);
    		// 	if(in_array($me['nick'], $apiAuthUserNicks)) {
    		// 		$managerAv = true;
    		// 	}
    		// }
    		if($managerId && !$managerAv){
    			throw new NewzanException('oauth授权不正确.', RetStatus::TOP_API_ERR);
    		} else{
	    		$me['oauth'] = $oauth;
	    		session('me' , $me);
	    		if($managerId) {
	    			$manager['oauth'] = $oauth;
	    			session('manager', $manager);
	    		} else {
	    			session('manager', NULL);
	    		}
    		}
    	}
    }
    
    public function getAuthorizedUsers($oauth = null)
    {
        // if($oauth) {
        //     $this->_api->setAccessToken($oauth['access_token']);
        // }
    	$resp = $this->_api->SimbaCustomersAuthorizedGetRequest(array(), $oauth ? $oauth['access_token'] : null);
    	return isset($resp['nicks']->string) ? $resp['nicks']->string : '';
    }
    
    /**
     * get a taobao user's information from taobao platform
     *
     * @param taobao_user_id
     */
    public function getUserByTaobaoId($taobao_user_id = 0)
    {
        $user = $this->field('user_id,type,nick,sex,desc,sid,cid,avatar,email,created_time,updated_time,qq,mobile,address,wangwang,init,balance,shop_score,purchased_from,purchase_expires,authorized_to,authorized_users,item_code, status,userfirst')->where("user_id = " . $taobao_user_id)->find();
        if(!$user){
            return false;
        }else{
            return $user;
        }
    }

    public function getAgentUserByTaobaoNick($keyword = '')
    {
        $current_user = self::getActiveUser();
        
        if(!$current_user) {
            return false;
        }
        $whr = "authorized_to = '".$current_user['oauth']['taobao_user_id']."'";
        if($keyword) {
            $whr .= " AND nick like '%".$keyword."%'";
        }/* else {
            $current_agent_users = $this->where("user_id = '".$current_user['oauth']['taobao_user_id']."'")->getField('authorized_users');
            $whr = "user_id IN(".$current_agent_users.")";
        }*/
        $users = $this->field('user_id,nick')->where($whr)->order('user_id DESC')->select();
        // die($this->getLastSql());
        if(!$users) {
            return false;
        } else {
            return $users;
        }
    }
    
    /**
     * 根据用户nick生产ID. 保证nick和id的一一对应.
     * @param string $nick
     * @return int 已经存在或者新产生的user_id. 一个负整数.
     */
    public function createAuthUserId($nick)
    {
    	$userHashMdl = M('user_nick_hash');
    	$existentHash = $userHashMdl->where( array( 'nick' => $nick) )->find();
    	if($existentHash) {
    		return 0 - $existentHash['user_id'];
    	} else {
    		$newId = $userHashMdl->add(array('nick' => $nick));
    		return 0 - $newId;
    	}
    }
    
    /**
     * 将用户$authrizedToUid的授权用户插入到初始状态表.
     * 
     * @param array(string) $authUsers 授权用户昵称数组
     * @param array(k=>v) $authrizedTo 授权给的用户.
     * 
     * @return array(int)
     */
    public function saveAuthUsers($authUsers, $authrizedTo)
    {
        if(!empty($authUsers) && $authrizedTo) {
    		$authrizedToUid = $authrizedTo['oauth']['taobao_user_id'];
	    	$userIds = array();
	    	$userHashMdl = M('user_nick_hash');
	    	foreach($authUsers as $newAuthUser) {
	    		//$existentUser = $userHashMdl->where( array( 'nick' => $newAuthUser) )->find();
	    		$existentUser = $this->where(array('nick'=>$newAuthUser))->find();
	    		
	    		if($existentUser) {
	    			$userIds[$newAuthUser] = $existentUser['user_id'];
	    			// 更新用户的经理帐号和过期时间列
	    			if($authrizedToUid != $existentUser['authorized_to'] 
	    					|| $existentUser['purchase_expires'] != $authrizedTo['purchase_expires']
	    					|| $existentUser['item_code'] != $authrizedTo['item_code'])
	    				$this->where('user_id=' . $existentUser['user_id'])->save(array(
	    						'authorized_to' => $authrizedToUid 
	    						//'purchase_expires' => $authrizedTo['purchase_expires']
	    						//'item_code' => $authrizedTo['item_code'],
	    				));
	    			
	    			// 如果以前为自动，现在为手动版本了，将自动推广组置为手动。
	    			if($existentUser['item_code'] != $authrizedTo['item_code'] && defined('MANUAL_VERSIONS')) {
	    				$manualVersions = explode(',', MANUAL_VERSIONS);
	    				// if(!in_array($existentUser['item_code'], $manualVersions)
	    				// 		&& in_array($authrizedTo['item_code'], $manualVersions)) {
	    				// 	$adMdl = new AdgroupModel();
	    				// 	$adMdl->checkManualUserAutoAds($existentUser['user_id']);
	    				// }
	    			}
	    			
	    			continue;
	    		}
	    		
	    		$data = array(
	    				'user_id' => $this->createAuthUserId($newAuthUser),
	    				'type' => '',
	    				'nick' => $newAuthUser,
	    				'sex' => '',
	    				'desc' => '',
	    				'avatar' => '/Img/default_avatar.jpg',
	    				'other' => '',
	    				'email' => '',
	    				'created_time' => date('Y-m-d H:i:s'),
	    				'authorized_to' => $authrizedToUid,
	    				'purchase_expires' => isset($authrizedTo['oauth']['purchase_expires']) ? $authrizedTo['oauth']['purchase_expires'] : '0000-00-00 00:00:00',
              'user_type' => 2
	    		);
    			$res = $this->add($data);
                $this->createTable($data['user_id']);
    			
	    		if($res === false) {
	    			throw_exception('DB异常: ' . $this->getDbError());
	    		} else {
	    			//++$addedNum;
	    			$userIds[$newAuthUser] = $data['user_id'];
	    		}
	    	}
	    	return $userIds;
    	} else {
    		return array();
    	}
    }
    
    /**
     * 利用API获取当前oauth卖家的信息
     * @param array $oauth
     * @return array
     */
    public function getUserByApi($oauth, $nick='')
    {
    	import("@.Library.TaobaoAPI.taobaoAPI");
      $taobaoAPI = taobaoAPI::login();

      $info = $taobaoAPI->UserSellerGetRequest(
    			array(
					'nick' => $nick,
          'fields' => 'user_id,nick,sex,seller_credit,type,has_more_pic,item_img_num,item_img_size,prop_img_num,prop_img_size,auto_repost,promoted_type,status,alipay_bind,consumer_protection,avatar,liangpin,sign_food_seller_promise,has_shop,is_lightning_consignment,has_sub_stock,is_golden_seller,vip_info,magazine_subscribe,vertical_market,online_gaming'
    			),
    			$oauth['access_token']
    	);
    	return $info; 
    }

    public function addUser($data)
    {
      //注册成功流程,1 写入users表
      $insert_id = $this->add($data);
      if($insert_id){
        return $data;
      }else{
        throw_exception($this->getDbError());
      }
    }

    /**
     * Generate negative random id.
     * 
     * @return number [-2147483646, -1000000], 
     */
    public static function randId()
    {
    	$id = mt_rand(1000000, 2147483646);
    	return -$id;
    }
    
    /**
     * 获取当前活动用户.
     * @return array 一条users表记录或者users_authorized表记录.
     */
    public static function getActiveUser()
    {
    	return session('me');
    }
    
    /**
     * 获取当前活动用户ID.
     * @return int
     */
    public static function getActiveUid()
    {
		$activeUser = self::getActiveUser();
		return $activeUser['user_id'];
    }
    
    /**
     * 根据用户ID获取自己获取的昵称, 或者用户的授权用户的昵称. 
     * 该方法只检查session, 不查数据库.
     * 
     * @param int $userId ,如果userid为0获取当前操作用户的nick
     * @return string|NULL 如果找到, 返回昵称; 否则返回null.
     */
    public static function getSelfOrAuthUserNick($userId = 0)
    {
    	$userId = $userId ? $userId : self::getActiveUid();
    	$manager = session('manager');	
    	$me = session('me');
    	if($userId == $me['user_id']) {
    		return $me['nick'];
    	}elseif( $userId == $manager['user_id']){
    	    return $manager['nick'];
    	} else {
    		return isset($manager['authorized_users'][$userId])
    			? $manager['authorized_users'][$userId] 
    			: null;
    	}
    }
	
    /**
     * 获取账户实时报表数据
     * @param  string   $nick   淘宝昵称
     * @return object   $data
     */
    public function getUserRealTimeCost($nick)
    {
        if(!$nick) {
            return false;
        }
        $params = array(
                'nick' => $nick,
                'the_date' => date('Y-m-d', time())
            );
        $data = $this->_api->SimbaRtrptCustGetRequest($params);
        return $data;
    }
	
    /**
     * 获取实时余额，”元”为单位
     * @return
     */
    public function getUserBalance()
    {
        $resp = $this->_api->SimbaAccountBalanceGetRequest();
        return $resp;
    }

    /**
     * 创建用户关键词表&&关键词报表表
     * @param  string   $user_id    用户编号
     * @return void
     */
    public function createTable($user_id)
    {
        // 报表 表sql
        $sql = "
            CREATE TABLE IF NOT EXISTS `rpt_keyword{$user_id}` (\n
              `taobao_user_id` bigint(64) NOT NULL,\n
              `campaign_id` int(11) NOT NULL,\n
              `adgroup_id` int(11) NOT NULL,\n
              `keyword_id` bigint(20) NOT NULL,\n
              `date` date NOT NULL DEFAULT '0000-00-00',\n
              `cpc` float NOT NULL DEFAULT '0',\n
              `ctr` float NOT NULL DEFAULT '0',\n
              `impressions` int(11) NOT NULL DEFAULT '0',\n
              `cpm` float NOT NULL DEFAULT '0',\n
              `click` int(11) NOT NULL DEFAULT '0',\n
              `cost` int(11) NOT NULL DEFAULT '0',\n
              `source` tinyint(4) NOT NULL DEFAULT '0' COMMENT '站内：1，站外：2 ，3: 汇总SUMMARY',\n
              `search_type` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0,SEARCH;1,CAT;2,NOSEARCH;3,ALL',\n
              `avgpos` float NOT NULL DEFAULT '0',\n
              `direct_pay` int(11) NOT NULL DEFAULT '0',\n
              `indirect_pay` int(11) NOT NULL DEFAULT '0',\n
              `direct_pay_count` int(11) NOT NULL DEFAULT '0',\n
              `indirect_pay_count` int(11) NOT NULL DEFAULT '0',\n
              `fav_shop_count` int(11) NOT NULL DEFAULT '0',\n
              `fav_item_count` int(11) NOT NULL DEFAULT '0',\n
              `direct_cart_total` int(11) NOT NULL,\n
              `keywordstr` varchar(256) NOT NULL,\n
              `indirect_cart_total` int(11) NOT NULL,\n
              `cart_total` int(11) NOT NULL,\n
              `qscore` int(11) NOT NULL DEFAULT '0',\n
              `wireless_qscore` int(11) NOT NULL DEFAULT '0',\n
              PRIMARY KEY (`keyword_id`,`date`,`source`,`search_type`,`adgroup_id`),\n
              KEY `rpt_keyword_date` (`date`) USING BTREE,\n
              KEY `k_rk_campaign_id` (`campaign_id`),\n
              KEY `k_rk_adgroup_id` (`adgroup_id`)\n
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        $this->execute($sql);

        // 关键词 表sql
        $sql ="
            CREATE TABLE IF NOT EXISTS `keywords{$user_id}` (\n
              `keyword_id` bigint(64) NOT NULL,\n
              `campaign_id` int(11) NOT NULL,\n
              `adgroup_id` int(11) NOT NULL,\n
              `qscore` int(11) NOT NULL DEFAULT '0',\n
              `wireless_qscore` int(11) NOT NULL DEFAULT '0',\n
              `matchscope` int(11) NOT NULL COMMENT '匹配模式',\n
              `nick` varchar(45) NOT NULL,\n
              `word` varchar(256) NOT NULL,\n
              `max_price` int(11) NOT NULL DEFAULT '500',\n
              `is_default_price` tinyint(1) NOT NULL,\n
              `audit_status` varchar(45) NOT NULL DEFAULT 'audit_pass' COMMENT '审核状态',\n
              `audit_desc` varchar(1024) DEFAULT NULL,\n
              `is_garbage` tinyint(1) NOT NULL DEFAULT '0',\n
              `create_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'api返回的创建时间',\n
              `modified_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'api返回的最后修改时间',\n
              `updated_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '系统对记录的更新时间',\n
              `order` smallint(6) NOT NULL,\n
              `rank_score` smallint(6) NOT NULL,\n
              `smart_price` tinyint(1) NOT NULL DEFAULT '0',\n
              `max_mobile_price` int(1) NOT NULL DEFAULT '0',\n
              `mobile_is_default_price` int(1) NOT NULL DEFAULT '1',\n
              PRIMARY KEY (`keyword_id`),\n
              KEY `k_k_adgroup` (`adgroup_id`) USING BTREE,\n
              KEY `k_k_campaign` (`campaign_id`)\n
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        $this->execute($sql);
    }
}